package com.fanghaoran.notes.controller;

import com.alibaba.fastjson.JSON;
import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.entity.Cart;
import com.fanghaoran.notes.entity.Product;
import com.fanghaoran.notes.entity.User;
import com.fanghaoran.notes.service.CartService;
import com.fanghaoran.notes.service.ProductService;
import com.fanghaoran.notes.service.impl.CartServiceImpl;
import com.fanghaoran.notes.service.impl.ProductServiceImpl;
import com.fanghaoran.notes.util.Constants;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: win11
 * @Date: 2023/04/22/14:04
 * @Description: 购物车controller
 */
@WebServlet("/cart")
public class CartController extends BaseServlet{
    /**
     * 获取service对象
     */
    CartService cartService=new CartServiceImpl();
    ProductService productService=new ProductServiceImpl();

    /**
     * 添加购物车
     */
    public void addCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前端传过来的pId
        String pId = request.getParameter("pId");
        //获取session中存储的用户
        User user=(User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //判断当前是否登录
        if (user == null) {
            //未登录
            response.getWriter().println(JSON.toJSONString(new MyResult(Constants.UN_LOGIN,"请先登录")));
        }else{
            //已登录 获取uId
            int uId=user.getUId();
            //根据uId和pId查询当前商品是否已在购物车
            Integer code = cartService.hasCart(uId, Integer.parseInt(pId)).getCode();
            if (code.equals(Constants.EMPTY)) {
                //不存在 执行添加操作
                //先获取商品数据
                @SuppressWarnings("unchecked")
                List<Product> products=(List<Product>) productService.getProductByPid(Integer.parseInt(pId)).getData();
                Product product=products.get(0);
                String pName = product.getPName();
                BigDecimal price = product.getPrice();
                //封装数据
                Cart cart1=new Cart();
                cart1.setPId(Integer.parseInt(pId));
                cart1.setUId(uId);
                cart1.setPName(pName);
                cart1.setPrice(price);
                cart1.setNum(1);
                //添加方法
                Integer result = cartService.addCart(cart1).getCode();
                if(result.equals(Constants.FAIL)) {
                    response.getWriter().println(JSON.toJSONString(new MyResult(Constants.FAIL,"添加失败")));
                }else{
                    response.getWriter().println(JSON.toJSONString(new MyResult(Constants.SUCCESS,"添加成功")));
                }
            }else{
                //存在 更新原始数据
                @SuppressWarnings("unchecked")
                List<Cart> carts=(List<Cart>) cartService.hasCart(uId, Integer.parseInt(pId)).getData();
                Cart cart=carts.get(0);
                //个数+1
                cart.setNum(cart.getNum()+1);
                Integer updateResult = cartService.updateCart(cart).getCode();
                if(updateResult.equals(Constants.FAIL)) {
                    response.getWriter().println(JSON.toJSONString(new MyResult(Constants.FAIL,"添加失败")));
                }else{
                    response.getWriter().println(JSON.toJSONString(new MyResult(Constants.SUCCESS,"添加成功")));
                }
            }
        }
    }

    /**
     * 更新购物车指定项商品个数
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void updateCartNum(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取前端传过来的pId
        String pId = request.getParameter("pId");
        //获取前端传过来的increment增量
        String increment = request.getParameter("increment");
        //获取session中存储的用户
        User user=(User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //获取uId
        int uId=user.getUId();
        //获取原始数据
        @SuppressWarnings("unchecked")
        List<Cart> carts=(List<Cart>) cartService.hasCart(uId, Integer.parseInt(pId)).getData();
        Cart cart=carts.get(0);
        //更新原始数据 并返回结果给前端
        cart.setNum(cart.getNum()+Integer.parseInt(increment));
        response.getWriter().println(JSON.toJSONString(cartService.updateCart(cart)));
    }

    /**
     * 展示购物车数据
     * @param request 请求
     * @param response 响应
     */
    public void showCart(HttpServletRequest request,HttpServletResponse response) throws Exception {
            //获取用户id
            User user=(User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
            int uId = user.getUId();
            //业务层获取购物车数据
            response.getWriter().println(JSON.toJSONString(cartService.showCart(uId)));
    }

    /**
     * 通过商品id删除购物车数据
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void deleteCartByPid(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //获取商品id
        String pId = request.getParameter("pId");
        //传给业务层删除数据 结果返回给前端
        response.getWriter().println(JSON.toJSONString(cartService.deleteCartByPid(Integer.parseInt(pId))));
    }

    /**
     * 清空购物车(删除uId部分的购物车)
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void removeAllCart(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取session中存储的用户
        User user=(User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //判断当前是否登录
        if (user == null) {
            //未登录
            response.getWriter().println(JSON.toJSONString(new MyResult(Constants.UN_LOGIN,"请先登录")));
        }else {
            //已登录 获取uId
            int uId = user.getUId();
            //业务层进行删除(通过uId) 结果返回给前端
            response.getWriter().println(JSON.toJSONString(cartService.removeAllCart(uId)));
        }
    }
}
